package behavioralPattern.interpret.example02;

import java.util.Deque;
import java.util.LinkedList;

/**
 * 表达式解释器类
 */
public class ExpressionInterpreter {
    private Deque<Expression> deque = new LinkedList<>();

    public long interpret(String expression) throws Exception {
        String[] split = expression.split(" ");

        int length = split.length;

        // 整理数字
        for (int i = 0; i < (length + 1) /2 ; ++i){
            deque.addLast(new NumExpression(split[i]));
        }

        // 整理符号
        for (int i = (length + 1) / 2 ; i < length; ++i){
            String operator = split[i];

            // 符号必须是 + - * /，否则异常
            boolean isValid = "+".equals(operator)
                    || "-".equals(operator)
                    || "*".equals(operator)
                    || "/".equals(operator);
            if (!isValid){
                throw new Exception("无效表达式！" + expression);
            }

            Expression exp_1 = deque.pollFirst();
            Expression exp_2 = deque.pollFirst();

            Expression result = null;
            if ("+".equals(operator)){
                result = new PluExpression(exp_1,exp_2);
            }else if ("-".equals(operator)){
                result = new SubExpression(exp_1,exp_2);
            }else if ("*".equals(operator)){
                result = new MulExpression(exp_1,exp_2);
            }else if ("/".equals(operator)){
                result = new DivExpression(exp_1,exp_2);
            }

            long num = result.interpret();

            deque.addFirst(new NumExpression(num));
        }

        // 注意：最终结果存储在集合中
        if (deque.size() != 1){
            throw new Exception("无效表达式！" + expression);
        }

        return deque.getFirst().interpret();
    }
}
